package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.etc.dao.ArticledetailMapper;
import com.etc.entity.Article;
import com.etc.entity.Articledetail;
import com.etc.entity.Comments;
import com.etc.entity.User;
import com.etc.service.ArticleService;
import com.etc.service.ArticledetailService;
import com.etc.service.CommentsService;
import com.etc.utils.FTPUtil;
import com.etc.utils.FileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 文章的controller
 * 
 * @author licheng
 *
 */
@Controller
public class ArticleController {
	// 分页大小
	final static int PAGESIZE = 5;
	// 正文排行的信息
	private List<Article> articleOrderByScoreList;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private ArticledetailService ariclArticledetailService;
	
	@Autowired
	private CommentsService commentsService;
	
	@RequestMapping("index")
	public String showIndex(){
		return "index";
	}

	@RequestMapping("md")
	public String md() {
		return "md";
	}

	@RequestMapping("news_add")
	public String showNewsAdd() {
		return "news_add";
	}

	@RequestMapping("news_add_success")
	public String showNewsAddSuccess() {
		return "news_add_success";
	}
	
	@RequestMapping("uploadTitleImage")
	@ResponseBody
	public String uploadTitleImage(@RequestParam("file") MultipartFile multipartFile){
		Random r = new Random();
		List<File> fileList = new ArrayList<File>();
		//对文件名重命名，加个随机数
		String fileName = multipartFile.getOriginalFilename();
		String[] split = fileName.split(".jpg");
		fileName = split[0] + r.nextInt(1000);
		fileName = fileName + ".jpg";
		
		
		File dest = new File("D:/upload/"+fileName);
		try {
			multipartFile.transferTo(dest);
			fileList.add(dest);
			boolean b = FTPUtil.uploadFile(fileList);
			if (b) {
				return "http://image.amall.com/img/"+fileName;
			}else{
				return null;
			}
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	@RequestMapping("news_detail/{articleid}")
	public String showNewsDetail(@PathVariable("articleid") Integer aid, Map<String, Object> map) {
		Article article = articleService.selectArticleByAid(aid);
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
		//浏览量+1
		article.setApageview(article.getApageview() + 1);
		articleService.updateArticle(article);
		
		//取出下一篇文章
		Article nextArticle = articleService.selectNextArticle(aid);
		
		List<List<Comments>> commentListList = commentsService.findAllCommentsByCid(aid);
		//计算该文章的评论数
		int countArticleComments = commentsService.countArticleComments(aid);
		
		map.put("article", article);
		map.put("date", sd.format(article.getAcreatetime()));
		map.put("nextArticle", nextArticle);
		map.put("countArticleComments", countArticleComments);
		map.put("commentListList", commentListList);
		return "news_detail";
	}

	/**
	 * 添加文章信息
	 * 
	 * @param article
	 * @return
	 */
	@RequestMapping(value = "addArticle", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> addArticle(@RequestBody() Article article,HttpSession session) {
		User user = (User) session.getAttribute("user");
		Map<String, String> map = new HashMap<>();
		if (user==null) {
			map.put("status", "tologin");
			return map;
		}
		article.setUser(user);

		article.setAcreatetime(new Timestamp(new Date().getTime()));
		int insertArticle = articleService.insertArticle(article);
		if (insertArticle > 0) {
			Articledetail record = new Articledetail();
			record.setAdid(article.getAid());
			record.setAddetail(article.getDetail());
			int i = ariclArticledetailService.insertArticledetail(record);
			if (i > 0) {
				map.put("status", "success");
			}
		} else {
			throw new RuntimeException("插入文章信息错误");
		}
		return map;
	}

	/**
	 * 图片上传
	 * 
	 * @param request
	 * @param response
	 * @param attach
	 * @return
	 */
	@RequestMapping("/imgUpload")
	@ResponseBody
	public String hello(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "editormd-image-file", required = true) MultipartFile[] attach) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html");
			
//			String savePath = "/upload/";
//			String path = FileUtil.saveMultiFile(savePath, attach);
			
			List<File> fileList = new ArrayList<File>();
			String filePath = null;
			for (MultipartFile multipartFile : attach) {
				File dest = new File("D:/upload/"+multipartFile.getOriginalFilename());
				filePath=multipartFile.getOriginalFilename();
				multipartFile.transferTo(dest);
				fileList.add(dest);
			}
			
			FTPUtil.uploadFile(fileList);
			
			ObjectMapper mapper = new ObjectMapper();
			HashMap<String, Object> map = new HashMap<>();
			map.put("success", 1);
			map.put("message", "上传成功");
			map.put("url", "http://image.amall.com/img/"+filePath);
			String s = mapper.writeValueAsString(map);
			return s;
			// 下面response返回的json格式是editor.md所限制的，规范输出就OK
			// response.getWriter().write(
			// "{\"success\": 1,
			// \"message\":\"上传成功\",\"url\":\"/resources/upload/"
			// + attach.getOriginalFilename() + "\"}" );
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.reset();
				response.getWriter().write("{\"success\":0}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return response.toString();
	}

	/**
	 * 对列表进行分页显示
	 * 
	 * @param pageNum
	 * @param request
	 * @return
	 */
	@RequestMapping("news")
	public String showAllArticle(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "order", required = false, defaultValue = "") String order,
			HttpServletRequest request) {
		// 查询文章信息并对文章进行分页
		PageHelper.startPage(pageNum, PAGESIZE);
		List<Article> articleInfoList = null;
		// 如果传过来的参数为“score”，则按评分进行排序
		if ("score".equals(order)) {
			articleInfoList = articleService.selectArticleOrderByAscore();
		} else {
			// 默认按时间进行排序
			articleInfoList = articleService.findAllArticleInfo();
		}
		PageInfo<Article> pageInfo = new PageInfo<Article>(articleInfoList);
		request.setAttribute("articleInfoList", articleInfoList);
		request.setAttribute("page", pageInfo);
		// 如果征文排行不为空，则进行查询
		if (articleOrderByScoreList == null) {
			articleOrderByScoreList = articleService.selectArticleOrderByPageview();
		}
		// 将排行信息传递出去
		request.setAttribute("articleOrderByScoreList", articleOrderByScoreList);
		return "news";
	}

}
